import argparse
import os
import uuid
from datetime import datetime
from pathlib import Path

import yaml

class Util:
    @staticmethod
    def get_project_dir():
        """获取工程根目录"""
        root = Path(__file__).resolve().parent.parent.parent
        return f"{root}{os.sep}"  # 使用系统分隔符

    @staticmethod
    def get_config_file_path():
        default_config_file = "config.yaml"
        """获取配置文件路径"""
        if os.path.exists(Util.get_project_dir() + "data/." + default_config_file):
            config_file = "data/." + default_config_file
        else:
            config_file = Util.get_project_dir() + default_config_file
        return config_file

    @staticmethod
    def get_config():
        """加载配置文件"""
        print(f"加载配置文件: {Util.get_config_file_path()}")
        parser = argparse.ArgumentParser(description="Server configuration")
        config_file = Util.get_config_file_path()
        parser.add_argument("--config_path", type=str, default=config_file)
        args = parser.parse_args()
        print(f"Loading configuration from {args.config_path}")
        with open(args.config_path, "r", encoding="utf-8") as file:
            config = yaml.safe_load(file)
        # 初始化目录
        Util.init_output_dirs(config)
        return config

    @staticmethod
    def init_output_dirs(config):
        """自动扫描所有层级的 output_dir 配置"""
        results = set()
        def _traverse(data):
            """递归遍历函数"""
            if isinstance(data, dict):
                # 先检查当前层级是否有 output_dir
                if "output_dir" in data:
                    results.add(data["output_dir"])
                # 继续深入遍历所有值
                for value in data.values():
                    _traverse(value)

            elif isinstance(data, list):
                # 遍历列表中的每个元素
                for item in data:
                    _traverse(item)

        _traverse(config)
        # 统一创建目录（保留原data目录创建）
        for dir_path in results:
            try:
                os.makedirs(Util.get_project_dir() + dir_path, exist_ok=True)
            except PermissionError:
                print(f"无法创建目录: {dir_path}")

    @staticmethod
    def get_random_file_path(dir_path: str, ex_name: str):
        """获取随机文件路径"""
        file_name = f"{datetime.now().date()}_{uuid.uuid4().hex}.{ex_name}"
        file_path = os.path.join(dir_path, file_name)
        return file_path

if __name__ == "__main__":
    print(Util.get_project_dir())
    Util.get_config()
    print(Util.get_random_file_path(Util.get_project_dir(), "mp3"))